package com.smartstate.ems.timedtask;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import com.alibaba.excel.EasyExcel;
import com.smartstate.ems.entity.PowerEquipmentEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

@Component
@Slf4j
public class MonthlyTasks {


    @Autowired
    private MonthlySummaryService monthlySummaryService;


    @Scheduled(cron = "0 0 0 30 * ? ")
    public void exportExcel() throws IOException {
        log.info("月电表开始记录");
        DateTime dateTime = new DateTime();
        System.out.println("dateTime = " + dateTime);
        DateTime startDate = dateTime.offsetNew(DateField.MONTH, -31);
        DateTime endDate = dateTime.offsetNew(DateField.MONTH, -1);
        List<PowerEquipmentEntity> power = monthlySummaryService.statisticsOnceAMonth(startDate, endDate);
        System.out.println("power = " + power);
//        ExcelUtils.export(response, "月电表数据", power, PowerEquipmentEntity.class);
        if (CollectionUtils.isEmpty(power) || power.size() <= 0) {
            log.info("空");
            return;
        }
        String fileName = "C://" + "simpleWrite" + System.currentTimeMillis() + ".xlsx";
        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
        // 如果这里想使用03 则 传入excelType参数即可
        EasyExcel.write(fileName, PowerEquipmentEntity.class).sheet("电表").doWrite(power);
        log.info("月电表记录结束");
    }


    private void setExcelRespProp(HttpServletResponse response, String rawFileName) throws UnsupportedEncodingException {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode(rawFileName, "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    }
}
